package cn.charlotte.pit.events.impl;

import cn.charlotte.pit.ThePit;
import cn.charlotte.pit.config.NewConfiguration;
import cn.charlotte.pit.data.PlayerProfile;
import cn.charlotte.pit.events.IEvent;
import cn.charlotte.pit.events.INormalEvent;
import cn.charlotte.pit.util.chat.CC;
import eu.decentsoftware.holograms.api.DHAPI;
import eu.decentsoftware.holograms.api.holograms.Hologram;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;

import java.util.*;

/**
 * @author Araykal
 * @since 2025/1/17
 */
public class DragonEggsEvent implements IEvent, INormalEvent, Listener {

    private Location eggLocation;
    private int clicks = 0;
    private Hologram hologram;
    private boolean isActive = false;
    private boolean isClickable = false;

    private static final int MIN_CLICKS = 50;
    private static final int EXTRA_CLICKS_PER_PLAYER = 2;
    private static final int CLICK_THRESHOLD = 30;
    private static final int SEARCH_RADIUS = 10;
    private static final int MAX_ATTEMPTS = 20;

    // ===== 1. 新增字段 =====
    private static final long CLICK_INTERVAL_MS      = 100;   // 合法间隔
    private static final long FAST_CLICK_MS          = 50;    // 判定为“超速”的阈值
    private static final int  FAST_CLICK_LIMIT       = 5;     // 超速累计上限
    private static final long COOLDOWN_MS            = 5_000; // 冷却时长

    private final Map<UUID, Long> lastClickTime  = new HashMap<>();
    private final Map<UUID, Integer> fastClicks  = new HashMap<>();
    private final Map<UUID, Long> cooldownUntil  = new HashMap<>();

    @Override
    public String getEventInternalName() {
        return "dragon_egg";
    }

    @Override
    public String getEventName() {
        return "&5龙蛋";
    }

    @Override
    public int requireOnline() {
        return NewConfiguration.getEventOnlineRequired().get(getEventInternalName());
    }

    /* ------------------------- 生命周期 ------------------------- */

    private void registerEvents() {
        Bukkit.getPluginManager().registerEvents(this, ThePit.getInstance());
    }

    private void unregisterEvents() {
        HandlerList.unregisterAll(this);
    }

    private int MAX_CLICKS = MIN_CLICKS;

    @Override
    public void onActive() {
        MAX_CLICKS = MIN_CLICKS + Bukkit.getOnlinePlayers().size() * EXTRA_CLICKS_PER_PLAYER;
        Location preset = ThePit.getInstance().getPitConfig().getEggLoc();
        if (preset == null) {
            broadcastMessage("&5&l龙蛋！ &7活动区域未设置，请联系管理员设置！");
            deactivateEvent();
            return;
        }
        eggLocation = preset.clone();
        isActive = true;
        isClickable = true;
        registerEvents();

        broadcastMessage("&5&l龙蛋！ &d龙蛋已在中心点位刷新,请前往点击！");
        setEggLocation(eggLocation);
        playSoundToPlayers(Sound.ENTITY_ENDER_DRAGON_GROWL, 1.5f, 1.5f);
        scheduleEventDeactivation();

        lastClickTime.clear();
        fastClicks.clear();
        cooldownUntil.clear();
    }

    private void scheduleEventDeactivation() {
        Bukkit.getScheduler().runTaskLater(
            ThePit.getInstance(),
            this::deactivateEvent,
            8 * 20 * 60L // 8 分钟后结束
        );
    }

    private void deactivateEvent() {
        ThePit.getInstance().getEventFactory().inactiveEvent(this);
        isActive = false;
        cleanup();
    }

    @Override
    public void onInactive() {
        unregisterEvents();
        cleanup();
        playSoundToPlayers(Sound.ENTITY_ENDER_DRAGON_DEATH, 1.5f, 1.5f);
        broadcastMessage("&5&l龙蛋！ &7活动已结束！");
    }

    private void cleanup() {
        if (eggLocation != null) {
            eggLocation.getBlock().setType(Material.AIR);
        }
        despawnHolograms();
        isActive = false;
        clicks = 0;
        lastClickTime.clear();
        fastClicks.clear();
        cooldownUntil.clear();
    }

    /* ------------------------- 核心逻辑 ------------------------- */

    private void setEggLocation(Location loc) {
        prepareLocation();
        eggLocation = loc.clone();
        eggLocation.getBlock().setType(Material.DRAGON_EGG);
        createHolograms(eggLocation);
    }

    private void prepareLocation() {
        if (eggLocation != null) {
            eggLocation.getBlock().setType(Material.AIR);
        }
    }

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        /* ---------- 基本过滤 ---------- */
        if (!isActive
                || event.getClickedBlock() == null
                || event.getClickedBlock().getType() != Material.DRAGON_EGG) {
            return;
        }

        // 拦截原版交互（防止龙蛋瞬移）
        event.setCancelled(true);

        /* ---------- 是否可点击 ---------- */
        if (!isClickable) {
            despawnHolograms();      // 清理悬浮字
            return;                  // 本轮点蛋结束
        }

        /* ---------- 频率限制 & 冷却 ---------- */
        Player player = event.getPlayer();
        UUID uid      = player.getUniqueId();
        long now      = System.currentTimeMillis();

        // 冷却检查
        Long until = cooldownUntil.get(uid);
        if (until != null && now < until) {
            long remain = (until - now + 999) / 1000; // 取整到秒
            player.sendActionBar(CC.translate("&c点击过快！冷却中 &e" + remain + "s"));
            return;
        }

        // 节奏与超速检测
        Long last  = lastClickTime.get(uid);
        long delta = (last == null) ? CLICK_INTERVAL_MS : now - last;

        if (delta < CLICK_INTERVAL_MS) {              // <100 ms：本次点击无效
            if (delta < FAST_CLICK_MS) {              // <50 ms：判定为“超速”
                int cnt = fastClicks.getOrDefault(uid, 0) + 1;
                fastClicks.put(uid, cnt);

                if (cnt >= FAST_CLICK_LIMIT) {        // 连续 5 次超速 → 5 s 冷却
                    cooldownUntil.put(uid, now + COOLDOWN_MS);
                    fastClicks.put(uid, 0);           // 重置计数
                    player.sendActionBar(CC.translate(
                            "&c诶！朋友！休息一会儿吧！"));
                }
            }
            return;                                   // 阻断后续正常逻辑
        }

        // 合法点击：刷新时间戳并清零超速计数
        lastClickTime.put(uid, now);
        fastClicks.put(uid, 0);

        /* ---------- 原本的点击逻辑 ---------- */
        PlayerProfile profile =
                PlayerProfile.getPlayerProfileByUuid(uid);
        handleClick(player, profile);   // 奖励金币/经验、更新全局 clicks
        updateClickState();             // 检查是否移动或结束活动
    }


    private void handleClick(Player player, PlayerProfile profile) {
        Random random = new Random();
        double randomMultiplier = random.nextDouble(3d) + 1d; // 1-3

        int coins;
        int exp;
        if (clicks == 0) {
            coins = (int) (3 * randomMultiplier);
            exp = (int) (3 * (random.nextDouble(4d) + 1d));
        } else {
            coins = (int) (clicks * 0.5d * randomMultiplier);
            exp = (int) (clicks * 0.5d * (random.nextDouble(4d) + 1d));
        }

        if (clicks <= MAX_CLICKS) {
            profile.setCoins(profile.getCoins() + coins);
            profile.setExperience(profile.getExperience() + exp);
        }

        player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1.5f, 1.5f);
        player.sendMessage(CC.translate("&5&l龙蛋！ &7点击龙蛋 获得 &e" + coins + " &6金币 &e" + exp + " &b经验&7"));
        clicks++;
        updateHolograms();
    }

    private void updateClickState() {
        if (clicks >= MAX_CLICKS) {
            deactivateEvent();
        } else if (clicks % CLICK_THRESHOLD == 0) {
            moveEggToNewLocation();
        }
    }

    private void moveEggToNewLocation() {
        prepareLocation();
        if (eggLocation != null) {
            setEggLocation(findRandomLocation(eggLocation));
        }
        broadcastMessage("&5&l龙蛋！ &7龙蛋已被移动到了新的位置！");
        playSoundToPlayers(Sound.ENTITY_ENDER_DRAGON_HURT, 1.5f, 1.5f);
        isClickable = true;
    }

    private Location findRandomLocation(Location origin) {
        Random random = new Random();
        for (int i = 0; i < MAX_ATTEMPTS; i++) {
        double x = origin.getX() + randomOffset(random);
        double z = origin.getZ() + randomOffset(random);
        Location newLoc = new Location(origin.getWorld(), x, origin.getY(), z);
        if (newLoc.getBlock().getType() == Material.AIR) {
            return newLoc;
        }
    }
        return origin;
    }

    private int randomOffset(Random random) {
        return random.nextInt(31) - SEARCH_RADIUS; // [-10, 20]
    }

    /* ------------------------- 工具方法 ------------------------- */

    private void broadcastMessage(String message) {
        Bukkit.broadcastMessage(CC.translate(message));
    }

    private void playSoundToPlayers(Sound sound, float volume, float pitch) {
        Bukkit.getOnlinePlayers().forEach(p -> p.playSound(p.getLocation(), sound, volume, pitch));
    }

    private void createHolograms(Location location) {
        if (hologram != null) {
            DHAPI.moveHologram(hologram.getName(), location.clone().add(0, 2, 0));
            hologram.getPage(0).setLine(0, "§a" + clicks + "§7/§e" + MAX_CLICKS);
        } else {
            hologram = DHAPI.createHologram("dragon_edd", location.clone().add(0, 2, 0), false, List.of("§a" + clicks + "§7/§e" + MAX_CLICKS, "§e§l点击"));
        }
    }

    private void updateHolograms() {
        if (hologram == null) {
            hologram = DHAPI.createHologram("dragon_edd", eggLocation.clone().add(0, 2, 0), false, List.of("§a" + clicks + "§7/§e" + MAX_CLICKS, "§e§l点击"));
        } else {
            hologram.getPage(0).setLine(0, "§a" + clicks + "§7/§e" + MAX_CLICKS);
        }
    }

    private void despawnHolograms() {
        DHAPI.removeHologram(hologram.getName());
    }
}
